package com.app.web.user.login;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.app.utils.base.http.ResultUtil;
import com.app.utils.base.j2se.Common;
import com.app.utils.base.j2se.JsonUtil;
import com.app.utils.base.j2se.Logger;
import com.app.utils.base.secret.AES;
import com.app.utils.base.secret.WxPKCS7Encoder;
import com.app.web.user.app.AppInfo;
import com.app.web.user.app.AppInfoManager;
import com.app.web.user.info.UserInfo;
import com.app.web.user.info.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Description
 * Created by 王伟
 * Date create on 15:12 2019/11/18.
 */
@RestController
@RequestMapping("/user/login/")
public class LoginController {
    @Autowired
    private LoginService loginModel;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 小程序登录,登录就注册为普通用户
     * @param code
     * @param user
     * @param encryptedData
     * @param iv
     * @param appKey
     * @param shareMcode
     * @param app
     * @return
     */
    @RequestMapping("xcx")
    public String loginXcx(@RequestAttribute String ip, String code, String user, String encryptedData, String iv, String appKey, @RequestParam(defaultValue = "74868") int shareMcode, @RequestParam(defaultValue = "0") int app){
        //参数判断
        if (StringUtils.isBlank(code) || StringUtils.isBlank(user)) {
            return ResultUtil.error("6001", "参数异常");
        }
        if(StringUtils.isBlank(encryptedData) || StringUtils.isBlank(iv) || StringUtils.isBlank(appKey)){
            return ResultUtil.error("6001", "参数异常");
        }
        //app判断
        AppInfo appInfo = AppInfoManager.get(appKey);
        if(null == appInfo){
            return ResultUtil.error("8002", "参数异常");
        }
        //组装微信登录信息
        LoginInfo wxLoginInfo = JsonUtil.jsonToBean(user, LoginInfo.class);
        try {
            WxMaJscode2SessionResult session = appInfo.getWxMaService().getUserService().getSessionInfo(code);
            byte[] resultByte = new AES().decryptStr(encryptedData, session.getSessionKey(), iv);
            if(null == resultByte) {
                return ResultUtil.error("8003","微信信息异常，解析失败");
            }
            String userInfo = new String(WxPKCS7Encoder.decode(resultByte));
            LoginInfo appUser1 = JsonUtil.jsonToBean(userInfo, LoginInfo.class);
            //没有绑定微信开放平台的小程序是获取不到UnionId的
            if(Common.isEmpty(appUser1.getUnionId())) {
                appUser1.setUnionId(appUser1.getOpenId());
//                return ResultUtil.error("8003","微信信息异常，解析失败:UnionId不存在");
            }
            wxLoginInfo.setAppId(appInfo.getApp_id());
            wxLoginInfo.setOpenId(session.getOpenid());
            wxLoginInfo.setUnionId(appUser1.getUnionId());
        } catch (Exception e) {
            Logger.error("小程序登录",e);
            return ResultUtil.error("8003","微信信息异常，解析失败");
        }
        return ResultUtil.success(login(wxLoginInfo, shareMcode, app,ip));
    }

    /**
     * 登录的公共逻辑
     * @param wxLoginInfo 微信登录新
     * @param shareMcode 来源mcode
     * @para app 应用id
     * @return 登录后的返回信息
     */
    private Map<String, Object> login(LoginInfo wxLoginInfo, int shareMcode, int app,String ip){
        //查询用户信息排除封号的用户
        LoginInfo loginInfo = loginModel.info(wxLoginInfo.getUnionId());
        if(null != loginInfo && loginInfo.hadblack()){
            return new HashMap<>();
        }
        UserInfo userInfo = userInfoService.info(wxLoginInfo.getId());
        //没有用户信息完成注册
        if(Common.isEmpty(loginInfo)){
            wxLoginInfo.setBind_mcode(shareMcode);
            wxLoginInfo.setCreate_time(new Date());
            loginModel.add(wxLoginInfo);
            //注册用户信息
            userInfo = userInfoService.addInfo(wxLoginInfo.getId(), shareMcode, ip);
        }else {
            wxLoginInfo.setId(loginInfo.getId());
            wxLoginInfo.setBind_mcode(Common.isEmpty(loginInfo.getBind_mcode())?shareMcode:loginInfo.getBind_mcode());
            if(userInfo.getMcode()==0){
                //注册用户信息
                userInfo = userInfoService.addInfo(wxLoginInfo.getId(), shareMcode, ip);
            }
        }
        //组装用户信息 返回用户信息和token
        //缓存登录信息
        loginModel.info(wxLoginInfo.getUnionId());
        return loginModel.loginUser(wxLoginInfo, userInfo);
    }
}
